import React, { useEffect } from "react";
import { Outlet, useNavigate } from "react-router-dom";
import TabBottom from "./components/TabBottom";
import EventBus from "./utils/EventBus";
import { useToast } from "./utils/toast";

export default function App() {
  //每次访问子路由，都是要经过App这个函数
  //就在这里进行判断，如果token存在，就放行，否则就阻止然后跳转到登录页面
  let token = localStorage.getItem("token");
  const toast = useToast();
  const navigate = useNavigate();
  useEffect(() => {
    if (!token) {
      // 提示
      toast("error", "请先登录");
      navigate("/login");
    }
    EventBus.on("logintimeout", () => {
      toast("error", "登录失效");
      // 把token清除
      localStorage.removeItem("token");
      // 登录失效，需要重新登录
      navigate("/login");
    });
  }, []);
  return (
    <div style={{ backgroundColor: "#fff", minHeight: "100vh" }}>
      {token ? (
        <>
          <Outlet />
          <TabBottom />
        </>
      ) : (
        <></>
      )}
    </div>
  );
}
